package leecode.字符串;

/**
 * @author wangxi created on 2021/5/31 23:17
 * @version v1.0
 *
 *  https://leetcode-cn.com/problems/multiply-strings/
 *
 *  字符串相乘
 */
public class MultiplyStrings {

    public String multiply(String s, String t) {
        // write code here
        if (s == null || s.length() <= 0 || t == null || t.length() <= 0) {
            return "";
        }
        if ("0".equals(s) || "0".equals(t)) {
            return "0";
        }
        int[] arr1 = new int[s.length()];
        int[] arr2 = new int[t.length()];
        int[] arr3 = new int[s.length() + t.length()];
        int count1 = 0;
        for (int i = s.length() - 1; i >= 0; i--) {
            arr1[count1] = Integer.parseInt(s.charAt(i) + "");
            count1++;
        }
        int count2 = 0;
        for (int i = t.length() - 1; i >= 0; i--) {
            arr2[count2++] = Integer.parseInt(t.charAt(i) + "");
        }
        for (int i = 0; i < arr1.length; i++) {
            for (int j = 0; j < arr2.length; j++) {
                arr3[i + j] += arr1[i] * arr2[j];
            }
        }
        int carry = 0;
        // 处理进位
        for (int i = 0; i < arr3.length; i++) {
            int a = carry + arr3[i];
            arr3[i] = a % 10;
            carry = a /10;
        }
        int j = arr3.length - 1;
        for (; j >= 0; j--) {
            if (arr3[j] != 0) {
                break;
            }
        }
        StringBuilder buffer = new StringBuilder();
        for (int i = j; i >= 0; i--) {
            buffer.append(arr3[i]);
        }
        return buffer.toString();
    }
}
